package com.game.primitive.context;

import com.game.common.MsgSendHelper;
import com.game.message.Msg;
import com.game.message.jpb.JPbUtil;
import com.game.message.jpb.SuperJPB;
import com.game.primitive.context.enums.BattleFieldStage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 战场
 * Created by lizhiwei on 2016/7/6.
 */
public class Battlefield extends AbstractLoop {
	private Map<Integer, PrimitivePlayer> playerMap = new ConcurrentHashMap<Integer, PrimitivePlayer>();
	private Map<Integer, Spirit> spiritMap = new ConcurrentHashMap<Integer, Spirit>();
	/**
	 * 战场所引用的场景
	 */
	private Scene scene;
	public void addPlayer(PrimitivePlayer player) {
		playerMap.put(player.getUserId(), player);
	}


	private BattleFieldStage stage = BattleFieldStage.READE;
	private int id;

	private boolean isCanDestroy = false;
	private long lastFlushTime = System.currentTimeMillis();

	private long currentMillSecond = BattleFieldStage.READE.getSecond();
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void loop(long now) {
		swithStage(now);
		if (stage == BattleFieldStage.READE) {
			readyStage();
		} else if (stage == BattleFieldStage.FIGHT) {
			fightStage();
		} else if (stage == BattleFieldStage.END) {
			endStage();
		}
	}

	/**
	 * 切换阶段
	 * @param now
	 */
	private void swithStage(long now) {
		currentMillSecond = currentMillSecond - (now - lastFlushTime);
		lastFlushTime = now;
		if (currentMillSecond <= 0) {
			if (stage == BattleFieldStage.READE) {
				stage = BattleFieldStage.FIGHT;
				currentMillSecond = stage.getSecond();
			} else if (stage == BattleFieldStage.FIGHT) {
				stage = BattleFieldStage.END;
				currentMillSecond = stage.getSecond();
			} else if (stage == BattleFieldStage.END) {
				destroy();
			}
		}
	}

	private void destroy() {
		for (PrimitivePlayer primitivePlayer : playerMap.values()) {
			primitivePlayer.clear();
		}
		isCanDestroy = true;
	}

	public boolean isCanDestroy() {
		return isCanDestroy;
	}

	/**
	 * 准备阶段刷帧频
	 */
	private void readyStage() {
	}

	/**
	 * 战斗阶段刷帧频
	 */
	private void fightStage() {
		move();
	}

	private void move() {
		for (Spirit spirit : spiritMap.values()) {
			//处理移动
		}
	}
	/**
	 * 结束阶段刷帧频
	 */
	private void endStage() {

	}
	/**
	 * 广播，这种小场景游戏，所有消息都广播
	 * @param superJPB
	 */
	public void broadcast(SuperJPB superJPB) {
		Msg msg = JPbUtil.getMsg(SuperJPB.class, superJPB);
		for (PrimitivePlayer primitivePlayer : playerMap.values()) {
			msg.setUserId(primitivePlayer.getUserId());
			MsgSendHelper.sendMsg(primitivePlayer.getCtx(), msg);
		}
	}
}
